import { useRenderStore } from '@/common/store';
import { NMMeshBaseCommand } from '@/common/types';
import { nmAppErrorLog } from '@/common/utils';
import i18n from '@/common/utils/i18next';
import { tool } from '@/domain';
import { EntityPartType } from '@amcax/web-render';
import { useAsyncEffect } from 'ahooks';
import { Tabs, TabsProps } from 'antd';
import { ManagerId } from 'nextcae-base';
import { Box } from 'nextcae-base/src/dialogs/component/Box';
import { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { MeshDialogProps } from '../cmd-seed-edit/type';
import { IQualityItem, MyTable } from './MyTable';
import './style.scss';

interface IQualityForm {
  '2D': IQualityItem[];
  '3D': IQualityItem[];
}

const WrapperStyle = styled.div`
  row-gap: 8px;
  padding: 15px;
  padding-bottom: 8px;
  display: flex;
  flex-direction: column;

  .form-dialog_footer {
    width: 100%;
    padding: 8px 0 12px !important;
  }

  ::-webkit-scrollbar {
    width: 6px;
    border-radius: 8px;
    /* background: white; */
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background-color: #99a9bf;
  }

  ::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 5px;
    background-color: #d3dce6;
  }
`;

// 网格质量检查
function CmdMeshQualityDialog({ title, onClose }: MeshDialogProps) {
  const { mainRenderer } = useRenderStore();
  const [currentTab, setCurrentTab] = useState('2D');
  const [qualityData, setQualityData] = useState<IQualityForm>({
    '2D': [],
    '3D': [],
  });
  // 保存id数组,用于重置单元的颜色
  const ids = useRef<number[]>([]);

  const resetColor = () => {
    // 上一次的网格质量显示重置
    const meshMgr = mainRenderer?.getEntityManager(ManagerId.Mesh);
    if (ids.current.length > 0) {
      meshMgr?.setEntityColor(
        undefined,
        undefined,
        EntityPartType.element,
        ids.current,
      );
    }
  };
  const render = async (params) => {
    try {
      const data = await tool.queryQuality(params);

      resetColor();

      if (data?.ids) {
        const meshMgr = mainRenderer?.getEntityManager(ManagerId.Mesh);
        meshMgr?.setEntityColor(
          0xff0000,
          undefined,
          EntityPartType.element,
          data?.ids,
        );
        ids.current = data?.ids;
      }
      mainRenderer.render();
    } catch (error) {
      nmAppErrorLog('render failed', error);
    }
  };
  useEffect(() => {
    return () => {
      resetColor();
    };
  }, []);
  useAsyncEffect(async () => {
    const formData = await tool.listQuality();
    setQualityData(formData);
  }, []);

  const onTabsChange = (key: string) => {
    setCurrentTab(key);
    // 根据currentSelectedRows判断是否选中，切换显示网格质量数据
  };

  const tabsItems: TabsProps['items'] = Object.keys(qualityData).map((key) => {
    const qualityItems: IQualityItem[] = qualityData[key];
    return {
      key,
      label: i18n.t(key),
      children: (
        <MyTable
          data={qualityItems}
          onItemChange={async (index, data, isSelected) => {
            const newQualityData = { ...qualityData };
            const newData = { ...data };
            delete newData['key']; // 不保存key
            newQualityData[key][index] = data;

            try {
              await tool.updateQuality(newQualityData);
              setQualityData(newQualityData);
              if (isSelected) {
                await render({ [key]: [data] });
              }
            } catch (error) {
              nmAppErrorLog(error);
            }
          }}
          onItemSelected={async (items) => {
            await render({ [key]: items });
          }}
        />
      ),
    };
  });

  return (
    <Box
      title={title}
      titleIcon={'commands/tool/meshQuality'}
      width={'400px'}
      onClose={onClose}>
      <WrapperStyle>
        <Tabs
          defaultActiveKey={currentTab}
          items={tabsItems}
          onChange={onTabsChange}
        />
      </WrapperStyle>
    </Box>
  );
}
// 网格质量检查
export const cmdMeshQuality: NMMeshBaseCommand = {
  id: 'CmdMeshQuality',
  icon: 'commands/tool/meshQuality',
  label: 'command.tool.meshQuality',
  create: (label: string, onClose: () => void, props) => (
    <CmdMeshQualityDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
